package com.hangzhou.xyj.ui.activity;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.engine.download.AjaxCallBack;
import com.hangzhou.xyj.engine.download.FinalHttp;
import com.hangzhou.xyj.event.AnimationEvent;
import com.hangzhou.xyj.model.type.EFileType;
import com.hangzhou.xyj.net.handler.ListenHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.request.ListenReq;
import com.hangzhou.xyj.ui.activity.base.BaseActivity;
import com.hangzhou.xyj.ui.listener.DownAudioListener;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.EventBusUtil;
import com.hangzhou.xyj.utils.LogUtil;
import com.hangzhou.xyj.utils.PublicUtil;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;
import com.mediaideas.videoengine.IMediaPlaybackService;
import com.mediaideas.videoengine.IMediaPlaybackStatusCallback;
import com.mediaideas.videoengine.lyrics.DefaultLrcBuilder;
import com.mediaideas.videoengine.lyrics.ILrcBuilder;
import com.mediaideas.videoengine.lyrics.ILrcView;
import com.mediaideas.videoengine.lyrics.LrcRow;
import com.mediaideas.videoengine.lyrics.LrcTask;
import com.mediaideas.videoengine.lyrics.LrcView;
import com.mediaideas.videoengine.lyrics.LyricLoader;
import com.mediaideas.videoengine.utils.FileUtils;
import com.mediaideas.videoengine.utils.MusicUtils;

import java.io.File;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by XieMing on 2016/3/19.
 */
public abstract class BasePlayActivity extends BaseActivity {
    protected final static int MSG_BTN_TIMER_HINT_SHOW = 0X0000;
    protected final static int MSG_BTN_TIMER_HINT_TEXT = 0X0001;
    protected final static int MSG_REFRESH_PROGRESS_POS = 0X0002;
    protected final static int MSG_MEDIA_PLAY_QUIT = 0X0003;
    protected final static int MSG_UPDATE_BTN_COLOR = 0X0004;
    protected final static int MSG_SHOW_MIXER_PROGRESS_VIEW = 0X0005;
    protected final static int REQUEST_CODE_PERMISSIONS = 0x0001;
    protected final static int MSG_TIME_COUNT_DONE = 0x0006;
    private final static String TAG = "BasePlayActivity";
    protected ProgressBar mProgressBar;
    protected MyTextView mCurrentTime;
    protected MyTextView mAudioDuration;
    protected View mProgressDlg;
    protected LrcView mLrcView;
    protected boolean mPause;
    protected Handler mHandler;
    protected long mDuration;
    protected Timer mLrcTimer;
    protected TimerTask mLrcTask;
    protected MusicUtils.ServiceToken mToken;
    protected IMediaPlaybackService mService = null;

    protected DownAudioListener mAudioDownListener; //下载音频监听器

    protected String mCurrentPlayFilePath; //当前正在播放的音频url
    protected OnMediaPlayerCompleteListener onMediaPlayerCompleteListener;
    OnServiceConnectedListener onServiceConnectedListener;
    // 播放器Service的链接回调
    protected ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            try {
                mService = IMediaPlaybackService.Stub.asInterface(iBinder);
                mService.setMediaPlaybackStatusCallback(mMediaPlaybackStatusCallback);
                if (onServiceConnectedListener != null)
                    onServiceConnectedListener.onServiceConnected();//服务连接完成
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mService = null;
        }
    };
    private boolean isPlayingRightDrama = true;//是否正在播放的曲目 和 当前进入的页面是相同曲目
    private int mPalyTimerDuration = 200;
    // 媒体播放器回调AIDL接口
    protected IMediaPlaybackStatusCallback mMediaPlaybackStatusCallback = new IMediaPlaybackStatusCallback.Stub() {
        @Override
        public void onMediaPlayBuffering(int percent) throws RemoteException {

        }

        /**
         * 播放完成
         * @throws RemoteException
         */
        @Override
        public void onMediaPlayerCompletion() throws RemoteException {
            stopLrcPlay();
            onMediaPlayerCompleteListener.onMediaPlayerComplete();
        }

        @Override
        public void onMediaPlayerError(int what, int extra) throws RemoteException {

        }

        @Override
        public void onMediaPlayerInfo(int what, int extra) throws RemoteException {

        }

        @Override
        public void onMediaPlayerPrepared() throws RemoteException {
            startLrcPlay();
        }

        @Override
        public void onMediaPlayerSeekComplete() throws RemoteException {

        }
    };

    public void setOnServiceConnectedListener(OnServiceConnectedListener listener) {
        this.onServiceConnectedListener = listener;
    }

    public void setIsPlayingRightDrama(boolean isPlayingRightDrama) {
        this.isPlayingRightDrama = isPlayingRightDrama;
    }

    public void setOnMediaPlayerCompleteListener(OnMediaPlayerCompleteListener listener) {
        this.onMediaPlayerCompleteListener = listener;
    }

    /**
     * 下载音频监听器
     *
     * @param listener
     */
    public void setOnDownAudioListener(DownAudioListener listener) {
        this.mAudioDownListener = listener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //下载文件的文件夹
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 绑定媒体播放service
        mToken = MusicUtils.bindToService(this, mServiceConnection);
        if (mToken == null) {
            // something went wrong
            mHandler.sendEmptyMessage(MSG_MEDIA_PLAY_QUIT);
        }
//        // 启动播放进度刷新
//        long next = startRefreshProgressHint();
//        sendNextRefreshMessage(next);
    }

    /**
     * 下载原唱
     *
     * @param nativeUrl
     */
    protected void downloadNative(String nativeUrl) {
        if (StringUtil.isBlank(nativeUrl)) {
            LogUtil.e(TAG, "下载原唱文件url 为空");
            return;
        }
        //1.prepare savepath
        String filePath = PublicUtil.getFilePath(nativeUrl, EFileType.AUDIO);

        //2.starting download
        FinalHttp fh = new FinalHttp();
        // 参数：第一个apk地址，第二个保存apk地址，第三个是否断点续传
        fh.download(nativeUrl, filePath, true, new AjaxCallBack<File>() {
            @Override
            public void onStart() {
                super.onStart();
                LogUtil.d(TAG, "原唱开始下载...");
//                showLoadingDialog(0);
                if (mAudioDownListener != null) {
                    mAudioDownListener.onDownAudioStart(DownAudioListener.AUDIO_NATIVE);
                }
            }

            @Override
            public void onFailure(Throwable t, int errorCode, String strMsg) {
                super.onFailure(t, errorCode, strMsg);
                if (!TextUtils.isEmpty(errorCode + "")
                        && errorCode == 416) {  //416表示download complete
                    LogUtil.d(TAG, "原唱文件已下载，无需重新下载......");
                    if (mAudioDownListener != null) {
                        mAudioDownListener.onDownAudioComplete(DownAudioListener.AUDIO_NATIVE);
                    }
                } else {
                    LogUtil.d(TAG, "原唱下载失败 errorCode " + errorCode + "msg:" + strMsg);
                    ToastUtil.show("原唱下载失败");
                }
//                hideLoadingDialog();
                if (mAudioDownListener != null) {
                    mAudioDownListener.onDownAudioFail(DownAudioListener.AUDIO_NATIVE);
                }
            }


            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
                int progress = (int) (current * 100 / count);
                LogUtil.d(TAG, "原唱正在下载  progress :" + progress);
                if (mAudioDownListener != null) {
                    mAudioDownListener.onDownloading(progress);
                }
//                showLoadingDialog(progress);
            }

            @Override
            public void onSuccess(File file) {
                super.onSuccess(file);
                LogUtil.d(TAG, "原唱下载成功");
//                hideLoadingDialog();
                if (mAudioDownListener != null) {
                    mAudioDownListener.onDownAudioComplete(DownAudioListener.AUDIO_NATIVE);
                }
            }
        });
    }

    /**
     * 下载伴奏
     *
     * @param accompanyUrl
     */
    protected void downloadAccompany(String accompanyUrl) {
        if (StringUtil.isBlank(accompanyUrl)) {
            LogUtil.e(TAG, "下载伴唱文件url 为空");
            return;
        }
        //1.prepare savepath
        String filePath = PublicUtil.getFilePath(accompanyUrl, EFileType.AUDIO);

        //2.starting download
        FinalHttp fh = new FinalHttp();
        // 参数：第一个apk地址，第二个保存apk地址，第三个是否断点续传
        fh.download(accompanyUrl, filePath, true, new AjaxCallBack<File>() {
            @Override
            public void onStart() {
                super.onStart();
                LogUtil.d(TAG, "伴唱开始下载...");
                showLoadingDialog(0);
                if (mAudioDownListener != null) {
                    mAudioDownListener.onDownAudioStart(DownAudioListener.AUDIO_ACCOMPANY);
                }
            }

            @Override
            public void onFailure(Throwable t, int errorCode, String strMsg) {
                super.onFailure(t, errorCode, strMsg);
                if (!TextUtils.isEmpty(errorCode + "")
                        && errorCode == 416) {  //416表示download complete
                    LogUtil.d(TAG, "伴唱文件已下载，无需重新下载......");
                    if (mAudioDownListener != null) {
                        mAudioDownListener.onDownAudioComplete(DownAudioListener.AUDIO_ACCOMPANY);
                    }
                } else {
                    LogUtil.d(TAG, "伴唱下载失败 errorCode " + errorCode + "msg:" + strMsg);
                    ToastUtil.show("伴唱下载失败");
                }
                hideLoadingDialog();
                if (mAudioDownListener != null) {
                    mAudioDownListener.onDownAudioFail(DownAudioListener.AUDIO_ACCOMPANY);
                }
            }


            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
                int progress = (int) (current * 100 / count);
                LogUtil.d(TAG, "伴唱正在下载  progress :" + progress);
                showLoadingDialog(progress);
            }

            @Override
            public void onSuccess(File file) {
                super.onSuccess(file);
                ToastUtil.show("下载成功");
                LogUtil.d(TAG, "伴唱下载成功");
                hideLoadingDialog();
                if (mAudioDownListener != null) {
                    mAudioDownListener.onDownAudioComplete(DownAudioListener.AUDIO_ACCOMPANY);
                }
            }
        });
    }

    /**
     * 下载歌词
     *
     * @param lrcUrl
     */
    protected void downloadLyric(final String lrcUrl) {
        if (StringUtil.isBlank(lrcUrl)) {
            LogUtil.e(TAG, "下载歌词文件url 为空");
            mLrcView.setLoadingTipText("该戏词不存在");
            return;
        }
        //1.prepare savepath
        String filePath = PublicUtil.getFilePath(lrcUrl, EFileType.LRC);

        //2.starting download
        FinalHttp fh = new FinalHttp();
        // 参数：第一个apk地址，第二个保存apk地址，第三个是否断点续传
        fh.download(lrcUrl, filePath, true, new AjaxCallBack<File>() {
            @Override
            public void onStart() {
                super.onStart();
                LogUtil.d(TAG, "歌词开始下载...");
//                mLrcView.setLoadingTipText("开始加载戏词...");
            }

            @Override
            public void onFailure(Throwable t, int errorCode, String strMsg) {
                super.onFailure(t, errorCode, strMsg);
                if (!TextUtils.isEmpty(errorCode + "")
                        && errorCode == 416) {  //416表示download complete
                    LogUtil.d(TAG, "歌词文件已下载，无需重新下载......");
                    //展示歌词
                    loadAndShowLRC(lrcUrl);
                } else {
                    LogUtil.d(TAG, "歌词下载失败，请重试.........");
                    mLrcView.setLoadingTipText("加载戏词失败");
                }
            }


            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
                int progress = (int) (current * 100 / count);
                LogUtil.d(TAG, "歌词正在下载  progress :" + progress);
                mLrcView.setLoadingTipText("正在加载戏词..." + progress + "%");
            }

            @Override
            public void onSuccess(File file) {
                super.onSuccess(file);
                ToastUtil.show("下载成功");
                LogUtil.d(TAG, "歌词下载成功");
                //展示歌词
                loadAndShowLRC(lrcUrl);
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        //解绑服务
        MusicUtils.unbindFromService(mToken);
        if (mHandler != null) {
            mHandler.removeMessages(MSG_REFRESH_PROGRESS_POS);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MusicUtils.unbindFromService(mToken);
//        stopLrcPlay();
//        stopPlayback();
    }


//    /**
//     * 横竖屏切换时候用，没有这种情况
//     * @param outState
//     */
//    @Override
//    public void onSaveInstanceState(Bundle outState) {
//        if (mDramaModel != null) {
//            outState.putSerializable(DataKey.DRAMA, mDramaModel);
//        }
//        super.onSaveInstanceState(outState);
//    }
//
//    /**
//     * 横竖屏切换时候用，没有这种情况
//     * @param savedInstanceState
//     */
//    @Override
//    protected void onRestoreInstanceState(Bundle savedInstanceState) {
//        savedInstanceState.getSerializable(DataKey.DRAMA);
//        super.onRestoreInstanceState(savedInstanceState);
//    }

    /**
     * 加载并显示歌词
     */
    public void loadAndShowLRC(final String lrcUrl) {
        new LyricLoader(this, new LyricLoader.Callback() {
            @Override
            public void onLoadLyricFinished(String result) {
                //歌词文本为空
                if (StringUtil.isBlank(result)) {
                    mLrcView.setLoadingTipText("该戏词文本不存在");
                } else {
                    settingLRC(result);
                }
            }
        }).execute(PublicUtil.getFilePath(lrcUrl, EFileType.LRC));
    }

    /**
     * 显示转圈进度对话框，指示正在保存或者加载
     */
    protected void showProgressDialog(String title) {
        Log.e(TAG, "showProgressDialog title=" + title);
        if (mProgressDlg == null) {
            mProgressDlg = findViewById(R.id.progress_dialog);
        }

        TextView titleView = ((TextView) mProgressDlg.findViewById(R.id.progress_title));
        titleView.setText(title);
        mProgressDlg.setVisibility(View.VISIBLE);
        mProgressDlg.bringToFront();
    }

    protected void dismissProgressDialog() {
        Log.e(TAG, "dismissProgressDialog");
        if (mProgressDlg != null) {
            mProgressDlg.setVisibility(View.GONE);
        }
    }

    // 获取前面一个播放音频的位置
    protected long getPrePlayPosition(String filePath) {
        if (mService == null) {
            return 0;
        }
        try {
            if (TextUtils.equals(mService.getPath(), filePath)) {
                return 0;
            }
            return mService.position();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return 0;
    }

    // 拖动播放进度
    protected void seekTo(long position) {
        try {
            if (mService != null && position > 0) {
                mService.seek(position);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 准备播放
     *
     * @param filePath
     */
    protected void initPlayBack(String filePath) {

        try {
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepare();
            mDuration = mediaPlayer.getDuration();
            mediaPlayer.release();
            mAudioDuration.setText(MusicUtils.makeTimeString(this, mDuration / 1000));
            mCurrentTime.setText(MusicUtils.makeTimeString(this, 0 / 1000));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 开始播放音频文件
    protected void startPlayback(String filePath) {
        if (mService == null || !FileUtils.isFileExists(filePath)) {
            return;
        }
        //保存当前播放的音频的url
        this.mCurrentPlayFilePath = filePath;
        try {
            if (TextUtils.equals(mService.getPath(), filePath)) {
                pausePlayback();
                return;
            }
            mService.stop();
            mService.openFile(filePath);
            mService.play();
            mDuration = mService.duration();
            mAudioDuration.setText(MusicUtils.makeTimeString(this, mDuration / 1000));
            long next = startRefreshProgressHint();
            sendNextRefreshMessage(next);
//            sendHandlerMessage(MSG_UPDATE_BTN_COLOR, filePath, -1, -1);
        } catch (RemoteException e) {
            e.printStackTrace();
            Log.d("MediaPlaybackActivity", "couldn't start playback: " + e);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 开始播放音频文件，适用于原唱/伴奏切换的情况
    protected void startPlayback(String filePath, long startPosition) {
        if (mService == null || !FileUtils.isFileExists(filePath)) {
            return;
        }
        //保存当前播放的音频的url
        this.mCurrentPlayFilePath = filePath;
        try {
            if (TextUtils.equals(mService.getPath(), filePath)) {
                pausePlayback();
                return;
            }
            mService.goToNext(mCurrentPlayFilePath);
            seekTo(startPosition);
            mDuration = mService.duration();
            mAudioDuration.setText(MusicUtils.makeTimeString(this, mDuration / 1000));
            long next = startRefreshProgressHint();
            sendNextRefreshMessage(next);
            sendHandlerMessage(MSG_UPDATE_BTN_COLOR, filePath, -1, -1);
        } catch (RemoteException e) {
            e.printStackTrace();
            Log.d("MediaPlaybackActivity", "couldn't start playback: " + e);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 停止播放
    protected void stopPlayback() {
        try {
            if (mService != null) {
                mService.stop();
                EventBusUtil.postEvent(new AnimationEvent(false));//左上角动画 暂停
                stopLrcPlay();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    // 暂停/播放
    protected void pausePlayback() {
        try {
            if (mService != null) {
                if (mService.isPlaying()) {
                    mService.pause();
                    stopLrcPlay();
                } else {
                    mService.play();
                    startLrcPlay();
                }
            }

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    // 是否正在播放
    protected boolean isMusicPlaying() {
        try {
            if (mService != null) {
                return mService.isPlaying();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return false;
    }

    protected void sendHandlerMessage(int what, Object obj, int arg1, int arg2) {
        if (mHandler != null) {
            Message msg = mHandler.obtainMessage();
            msg.what = what;
            msg.obj = obj;
            msg.arg1 = arg1;
            msg.arg2 = arg2;
            mHandler.sendMessage(msg);
        }
    }

    // 发送进度刷新消息
    protected void sendNextRefreshMessage(long delay) {
        if (!mPause && mHandler != null && isPlayingRightDrama) {
            Message msg = mHandler.obtainMessage(MSG_REFRESH_PROGRESS_POS);
            mHandler.removeMessages(MSG_REFRESH_PROGRESS_POS);
            mHandler.sendMessageDelayed(msg, delay);
        }
    }

    /**
     * 是否正在播放
     *
     * @return
     */
    protected boolean hasPlaying() {
        try {
            if (mService != null && mService.isPlaying()) {
                return true;
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return false;
    }

    protected float getVolume() {
        try {
            if (mService != null) {
                float volume = mService.getVolume();
                Log.e(TAG, "get volume:" + volume);
                return volume;
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return -1.0F;
    }

    // 设置播放音量
    protected void setVolume(float volume) {
        try {
            if (mService != null) {
                Log.e(TAG, "set volume:" + volume);
                mService.setVolume(volume);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    protected long startRefreshProgressHint() {
        return 500;
    }

    // 开始启动播放歌词刷新
    protected void startLrcPlay() {
        if (mLrcTimer == null && mLrcView != null) {
            mLrcTimer = new Timer();
            mLrcTask = new LrcTask(mLrcView, mService);
            mLrcTimer.scheduleAtFixedRate(mLrcTask, 0, mPalyTimerDuration);
        }
    }

    // 停止歌词刷新
    protected void stopLrcPlay() {
        if (mLrcTimer != null) {
            mLrcTimer.cancel();
            mLrcTimer = null;
        }
        if (mLrcTask != null) {
            mLrcTask.cancel();
            mLrcTask = null;
        }
    }

    /**
     * 加载歌词内容
     *
     * @param contentLrc 歌词内容
     */
    protected void settingLRC(String contentLrc) {
        if (mLrcView == null) {
            return;
        }
        ILrcBuilder builder = new DefaultLrcBuilder();
        List<LrcRow> rows = builder.getLrcRows(contentLrc);
        if (mLrcView != null) {
            mLrcView.setLrc(rows);
            mLrcView.setListener(new ILrcView.LrcViewListener() {

                public void onLrcSeeked(int newPosition, LrcRow row) {
                    try {
                        int time = (int) row.time;
                        if (mService != null && mService.position() > time) {
                            mService.seek(row.time);
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 发送统计播放id
     *
     * @param listenId 被听对象id
     * @param userId   用户id，可以不传
     */
    public void sendListeneReq(long listenId, long userId) {
        ListenReq req;
        if (userId < 0) {
            req = new ListenReq(listenId, userId);
        } else {
            req = new ListenReq(listenId);
        }
        //该请求只管发送，不需要处理
        HttpLoader.getInstance().sendRequest(new ListenHandler(req, null, 0));
    }

//    /**
//     * 播放完成
//     */
//    public void onMediaPlayerCompletion() {
//
//    }

    protected interface OnServiceConnectedListener {
        void onServiceConnected();
    }

    protected interface OnMediaPlayerCompleteListener {
        void onMediaPlayerComplete();
    }
}
